﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Threading;

namespace FlightSearchServer
{
    class ServerData
    {
        public static Dictionary<string, TicketSellingServiceClient> sellingServers 
                        = new Dictionary<string, TicketSellingServiceClient>();
        //using multiple readers-single writer lock
        // to provide proper sellingServers access
        public static ReaderWriterLock sellingServersLock = new ReaderWriterLock();


        public static Boolean AddSellingServer(string name, string url)
        {
            sellingServersLock.AcquireWriterLock(Timeout.Infinite);

            try
            {
                TicketSellingServiceClient proxy =
                new TicketSellingServiceClient(new BasicHttpBinding(), new EndpointAddress(url));
                sellingServers.Remove(name);
                sellingServers.Add(name, proxy);
            }
            catch (Exception)
            {
                //couldn't create proxy
                sellingServersLock.ReleaseWriterLock();
                return false;
            }
            
            sellingServersLock.ReleaseWriterLock();
            
            return true;
         }

        public static Boolean RemoveSellingServer(string name)
        {
            sellingServersLock.AcquireWriterLock(Timeout.Infinite);

            try
            {
                TicketSellingServiceClient proxy = sellingServers[name];
                proxy.Close();
                sellingServers.Remove(name);
            }
            catch (Exception)
            {
                //couldn't find proxy, or proxy is bad
                sellingServersLock.ReleaseWriterLock();
                return false;
            }
            
            sellingServersLock.ReleaseWriterLock();
            
            return true;
        }
    }
}
